package com.lgd.factoryattendance.View;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import com.lgd.factoryattendance.R;

/**
 * @Author lgd
 * @Date 2024/7/4 10:38
 */
public class LoaringDialog extends Dialog {
    private ImageView iv_ing;
    private AnimationSet animationSet;
    private static volatile LoaringDialog instance;

    public static LoaringDialog getInstance(Context context) {
        if (instance == null) {
            synchronized (LoaringDialog.class) {
                if (instance == null) {
                    instance = new LoaringDialog(context);
                }
            }
        }
        return instance;
    }

    private LoaringDialog(@NonNull Context context) {
        super(context, android.R.style.Theme_DeviceDefault_Light_Dialog_NoActionBar);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initWindowProperties();
        setContentView(R.layout.dialog_loading);

        iv_ing = findViewById(R.id.iv_ing);
        animationSet = createRotationAnimation();

        setCancelable(true);
        setCanceledOnTouchOutside(false);
    }

    private void initWindowProperties() {
        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getWindow().setDimAmount(0f);
        getWindow().setFlags(
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        );
    }

    private AnimationSet createRotationAnimation() {
        AnimationSet set = new AnimationSet(true);
        RotateAnimation rotate = new RotateAnimation(0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotate.setRepeatCount(Animation.INFINITE);
        rotate.setDuration(1000);
        rotate.setInterpolator(new LinearInterpolator());
        set.addAnimation(rotate);
        return set;
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (iv_ing != null && animationSet != null) {
            iv_ing.startAnimation(animationSet);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (iv_ing != null) {
            iv_ing.clearAnimation();
        }
        if (animationSet != null) {
            animationSet.cancel();
            animationSet = null;
        }
    }

}
